package com.test.javafaq_portal.controller;

import com.test.javafaq_portal.service.IUserService;
import com.test.javafaq_portal.service.ServiceException;
import com.test.javafaq_portal.vo.R;
import com.test.javafaq_portal.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
public class SystemController {

    @Value("${javafaq.resources.path}")
    private File resourcePath;

    @Value("${javafaq.resources.host}")
    private String resourceHost;

    @Autowired
    IUserService userService;


    @PostMapping("/upload/image")
    public R<String> uploadImage(MultipartFile imageFile) throws IOException {
         //服务器每天新建一个文件夹保存当天上传的文件，方便管理
        //文件夹按照 年\月\日
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        // path = 2025/4/25
        //创建文件夹
        File folder = new File(resourcePath,path);
        folder.mkdirs();
        log.debug("上传的文件夹为：{}",folder.getAbsolutePath());
        //文件夹已经确定了， 文件名和后缀西药我们设计:文件名随机 ， 后缀不变
        // abc.jpg
        // xxxxsfsfssasfsfa.jgp
        //获取原始文件名
        String filename = imageFile.getOriginalFilename(); //abc.jpg
        //获取扩展名
        String ext = filename.substring(filename.lastIndexOf(".")); //.jpg
        log.debug("文件名：{},后缀名：{}",filename,ext);

        //生成随机文件名 UUID
        String name = UUID.randomUUID().toString() + ext; // xxxxsfsfssasfsfa.jgp
        File file = new File(folder,name); // d:/upload/2025/4/25/xxxxsfsfssasfsfa.jgp
        log.debug("最终文件名:{}",file.getAbsolutePath());
        //写入文件
        imageFile.transferTo(file);
        //返回静态资源服务器访问图片的路径
        String url = resourceHost + "/" + path + "/"+name;
        // d:/upload/a.png      >   localhost:8899/a.png

        return R.ok(url);
    }

    @PostMapping("/upload/file")
    public R<String> upload(MultipartFile imageFile) throws IOException {
        File folder = new File("D:/upload");

        String filename = imageFile.getOriginalFilename();

        File file = new File(folder,filename);

        imageFile.transferTo(file);
        return R.ok("上传完成");
    }

    @PostMapping("/register")
    public R registerStudent(@Validated RegisterVo registerVo, BindingResult res){
        //@Validated RegisterVo registerVo 表示要验证RegisterVo
        //BindingResult 来保存验证结果

        if(res.hasErrors()){//如果有错误
            String error = res.getFieldError().getDefaultMessage();
            return R.unproecsableEntity(error);
        }
        if(!registerVo.getPassword().equals(registerVo.getConfirm())){
            return R.unproecsableEntity("两次密码输入不一致");
        }

        log.debug("得到表单:{}",registerVo);
        try {
            userService.registerStudent(registerVo);
            return R.created("注册成功");
        }catch (ServiceException e){
            return R.failed(e);
        }
    }

    @GetMapping("/register.html")
    public ModelAndView regForm(){
        return new ModelAndView("register");
    }

    @GetMapping("/login.html")
    public ModelAndView loginForm(){
        return new ModelAndView("login");
    }

}
